package com.stylefeng.guns.modular.customer.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.support.DateTimeKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.customer.dao.VisitDao;
import com.stylefeng.guns.modular.customer.service.IVisitPicService;
import com.stylefeng.guns.modular.customer.service.IVisitService;
import com.stylefeng.guns.modular.customer.warpper.PayPlanWrapper;
import com.stylefeng.guns.modular.customer.warpper.VisitWrapper;
import com.stylefeng.guns.modular.system.model.Visit;
import com.stylefeng.guns.modular.system.model.VisitPic;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.NoPermissionException;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 拜访记录控制器
 *
 * @author fengshuonan
 * @Date 2018-04-14 16:48:12
 */
@Controller
@RequestMapping("/visit")
public class VisitController extends BaseController {

    private String PREFIX = "/customer/visit/";

    @Autowired
    private IVisitService visitService;

    @Autowired
    private VisitDao visitDao;

    @Autowired
    private IVisitPicService visitPicService;

    /**
     * 跳转到拜访记录首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "visit.html";
    }

    /**
     * 跳转到添加拜访记录
     */
    @RequestMapping("/visit_add")
    public String visitAdd() {
        return PREFIX + "visit_add.html";
    }

    /**
     * 跳转到修改拜访记录
     */
    @RequestMapping("/visit_update/{visitId}")
    public String visitUpdate(@PathVariable Integer visitId, Model model) {
        Visit visit = visitService.selectById(visitId);
        Map<String, Object> map = BeanKit.beanToMap(visit);
        addPic(map);
        model.addAttribute("item", new VisitWrapper(map).warp());
        LogObjectHolder.me().set(visit);
        return PREFIX + "visit_edit.html";
    }

    @RequestMapping("/visit_pic_show/{visitId}")
    public String picShow(@PathVariable Integer visitId, Model model) {
        List<VisitPic> pics = visitPicService.selectByVisitId(visitId);
        model.addAttribute("pics", pics);
        return PREFIX + "visit_pic_show.html";
    }



    /**
     * 获取拜访记录列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(
            @RequestParam(value = "customerCompanyId",required = false) Integer customerCompanyId,
            @RequestParam(required = false) String begin_visitDate,
            @RequestParam(required = false) String end_visitDate,
            @RequestParam(required = false) String key,
            @RequestParam(required = false) Integer feedback,
            @RequestParam(required = false) Integer createByMe) {
        Page<Visit> page = new PageFactory<Visit>().defaultPage();
        Integer creatorId = null;
        if (createByMe != null && createByMe == 1) {
            creatorId = ShiroKit.getUser().getId();
        }
        List<Map<String, Object>> result = this.visitDao.page(page, customerCompanyId ,creatorId ,begin_visitDate,end_visitDate, key, feedback);
        page.setRecords((List<Visit>) new VisitWrapper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 新增拜访记录
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    @ApiOperation(value="新增拜访记录",tags = "拜访记录",httpMethod="POST",code = 200,response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "customerCompanyId", value = "企业名称", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "Date", required = true),
                    @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "Date", required = true),
                    @ApiImplicitParam(name = "place", value = "地点", dataType = "String", required = false),
                    @ApiImplicitParam(name = "form", value = "形式（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "target", value = "拜访目的", dataType = "String", required = false),
                    @ApiImplicitParam(name = "targetPerson", value = "拜访对象", dataType = "String", required = true),
                    @ApiImplicitParam(name = "summary", value = "拜访纪要", dataType = "String", required = true),
                    @ApiImplicitParam(name = "nextStep", value = "下一步措施", dataType = "String", required = true),
                    @ApiImplicitParam(name = "challengesAndOpportunities", value = "主要机会和存在问题", dataType = "String", required = false),
                    @ApiImplicitParam(name = "feedback", value = "产品反馈(字典数据)", dataType = "String", required = false),
                    @ApiImplicitParam(name = "urls",value = "图片地址",dataType = "string[]",required = false)

            }
    )
    public Object add(@Valid Visit visit, @RequestParam(value = "urls[]",required = false)String[] urls) {
        validTime(visit.getBeginTime(), visit.getEndTime());
        visit.setCreatorName(ShiroKit.getUser().getName());
        visit.setCreatorId(ShiroKit.getUser().getId());
        visit.setVisitorId(ShiroKit.getUser().getId());
        visitService.insert(visit, urls);
        return SUCCESS_TIP;
    }

    /**
     * 删除拜访记录
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Permission(Const.ADMIN_NAME)
    public Object delete(@RequestParam Integer visitId) {
        visitService.deleteById(visitId);
        return SUCCESS_TIP;
    }

    /**
     * 修改拜访记录
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    @ApiOperation(value = "修改拜访记录", tags = "拜访记录", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
                    {
                            @ApiImplicitParam(name = "customerCompanyId", value = "企业名称", dataType = "Integer", required = true),
                            @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true),
                            @ApiImplicitParam(name = "customerCompanyId", value = "企业名称", dataType = "Integer", required = true),
                            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "Date", required = true),
                            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "Date", required = true),
                            @ApiImplicitParam(name = "place", value = "地点", dataType = "String", required = false),
                            @ApiImplicitParam(name = "form", value = "形式（字典数据）", dataType = "String", required = true),
                            @ApiImplicitParam(name = "target", value = "拜访目的", dataType = "String", required = false),
                            @ApiImplicitParam(name = "targetPerson", value = "拜访对象", dataType = "String", required = true),
                            @ApiImplicitParam(name = "summary", value = "拜访纪要", dataType = "String", required = true),
                            @ApiImplicitParam(name = "nextStep", value = "下一步措施", dataType = "String", required = true),
                            @ApiImplicitParam(name = "challengesAndOpportunities", value = "主要机会和存在问题", dataType = "String", required = false),
                            @ApiImplicitParam(name = "feedback", value = "产品反馈（字典数据）", dataType = "String", required = false),
                            @ApiImplicitParam(name = "urls",value = "图片地址",dataType = "string[]",required = false)
                    }
            )

    public Object update(@Valid Visit visit,
                         @RequestParam(value = "urls[]",required = false) String[] urls) throws NoPermissionException {
        if(!validEditPermission(visit)){
            throw new NoPermissionException();
        }
        validTime(visit.getBeginTime(), visit.getEndTime());
        visitService.updateById(visit, urls);
        return SUCCESS_TIP;

    }


    private boolean validEditPermission(Visit visit) {
        Visit v = this.visitService.selectById(visit.getId());
        if (v == null) {
            return true;
        }
        if (v.getCreatorId().equals(ShiroKit.getUser().getId())) {
            return true;
        }
        return false;
    }


    @RequestMapping(value = "/visit_detail/{customerCompanyId}")
    public Object toDetail(@PathVariable("customerCompanyId") Integer customerCompanyId, Model model) {
        List<Map<String, Object>> list = visitDao.selectByCompanyId(customerCompanyId);
        model.addAttribute("items", new VisitWrapper(list).warp());
        return PREFIX + "visit_detail.html";
    }


    /**
     * 拜访记录详情
     */
    @RequestMapping(value = "/detail/{visitId}")
    @ResponseBody
    public Object detail(@PathVariable("visitId") Integer visitId) {
        Visit visit = visitService.selectById(visitId);

        if (visit == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }

        Map<String, Object> map = BeanKit.beanToMap(visit);

        if (validEditPermission(visit))
            map.put(Const.AUTHORITY_FIELD_NAME, 1);
         else
            map.put(Const.AUTHORITY_FIELD_NAME, -1);

        addPic(map);
        return new VisitWrapper(map).warp();
    }

    private void validTime(String beginTime, String endTime) {
        if (DateTimeKit.parseTime(beginTime).after(DateTimeKit.parse(endTime))) {
            throw new GunsException(400, "开始时间不能大于结束时间");
        }
    }

    private void addPic(Map<String,Object> map) {
        List<VisitPic> list = visitPicService.selectByVisitId((Integer) map.get("id"));
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> urlList = new ArrayList<>(list.size());
            map.put("pic", urlList);
            for (VisitPic pic : list) {
                urlList.add(pic.getUrl());
            }
        }else {
            map.put("pic", Collections.EMPTY_LIST);
        }

    }
}
